﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using UCL;
using UCL.Forms;
using UCL.IO;

namespace UAS5.UControls
{
    /// <summary>
    /// 图标选项卡控件
    /// </summary>
    /// <remarks>2014-2-12 by sutroon</remarks>
    public partial class ucIconTabControl : UserControl
    {
        /// <summary>
        /// 获取或设置图标运行的委托方法
        /// <para>参数:name,path,tag,image</para>
        /// </summary>
        public Action<string, string, string, Image> StartIconHandler { get; set; }

        /// <summary>
        /// 获取或设置是否显示边栏按钮
        /// </summary>
        /// <remarks>2014-2-27 by sutroon</remarks>
        public bool ShowSideButton
        {
            get { return btnNext.Visible; }
            set
            {
                btnNext.Visible = value;
                btnPrev.Visible = value;
                if (value)
                {
                    tabctrlMain.Location = new Point(btnPrev.Width, 0);
                    tabctrlMain.Size = new Size(this.Width - btnPrev.Width - btnNext.Width, this.Height);
                }
                else
                {
                    tabctrlMain.Location = new Point(0, 0);
                    tabctrlMain.Size = this.Size;
                }
            }
        }

        int currentTabIndex = 2;
        ImageList imgs;
        ClickEventHelper ceh;
        AppDataHelper adh;
        public ucIconTabControl()
        {
            InitializeComponent();

            ceh = new ClickEventHelper();
            cmiClickConfig();
            ceh.DoubleClickEventHandler = lvDoubleClick;
            cmsIcon.Opening += cmsIcon_Opening;
            tabctrlMain.SelectedIndexChanged += new EventHandler(tabctrlMain_SelectedIndexChanged);

            btnNext.Click += new EventHandler(btn_Click);
            btnPrev.Click += new EventHandler(btn_Click);
        }
        public void uc_init()
        {
            adh = new AppDataHelper();
            FormLoad();
        }

        public void FormLoad()
        {
            if (tabctrlMain.TabCount > 1)
            {
                int i = tabctrlMain.TabCount - 1;
                while (i > 0)
                {
                    tabctrlMain.TabPages.RemoveAt(i);
                    i--;
                }
            }
            TabPage tp;
            DataTable dtTags = adh.ExecuteDataTable("select Name,Content from tgeneralcatalog where SiteTag='quickdial' order by Ordinal");
            dtTags.PrependRowR("所有应用", "");
            ListView lv;
            imgs = new ImageList();
            imgs.ImageSize = new Size(32, 32);
            imgs.ColorDepth = ColorDepth.Depth32Bit;
            foreach (DataRow r in dtTags.Rows)
            {
                tp = new TabPage() { Text = r[0].ToString(), Tag = r[1], BackColor = Color.White };
                lv = new ListView() { Dock = DockStyle.Fill, ContextMenuStrip = cmsIcon, ShowItemToolTips = true };
                lv.MouseDown += new MouseEventHandler(lv_MouseDown);
                tp.Controls.Add(lv);
                tabctrlMain.TabPages.Add(tp);
            }
            if (currentTabIndex > 0 && currentTabIndex < tabctrlMain.TabCount - 1) tabctrlMain.SelectedIndex = currentTabIndex;
            FormLoad_Icons();

        }

        /// <summary>
        /// 加载图标列表
        /// </summary>
        public void FormLoad_Icons()
        {
            if (tabctrlMain.SelectedIndex < 1) return;
            ListView lv = (ListView)tabctrlMain.SelectedTab.Controls[0];
            lv.Items.Clear();
            imgs.Images.Clear();
            imgs.Images.Add("file", AppRes.file32);
            imgs.Images.Add("folder", AppRes.folder32);
            imgs.Images.Add("link", AppRes.link32);
            imgs.Images.Add("warning", AppRes.warning);
            lv.LargeImageList = imgs;
            DataTable dtIcons;
            string path, title;
            if (tabctrlMain.SelectedIndex == 1)
            {
                dtIcons = adh.ExecuteDataTable(string.Format("select a.ID,a.Name,a.Paths,a.IconPath,b.Content from tquickdial a left join tgeneralcatalog b on a.Tags=b.Name order by a.Name", tabctrlMain.SelectedTab.Text));
            }
            else
            {
                dtIcons = adh.ExecuteDataTable(string.Format("select a.ID,a.Name,a.Paths,a.IconPath,b.Content from tquickdial a left join tgeneralcatalog b on a.Tags=b.Name where a.Tags='{0}' order by a.Ordinal", tabctrlMain.SelectedTab.Text));
            }
            lv.SuspendLayout();
            Image icon;
            foreach (DataRow r2 in dtIcons.Rows)
            {
                path = r2["Paths"].ToString();
                title = r2["Name"].ToString().SubText(0, 10);
                if (path.Length == 0)
                {
                    lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = "warning" });
                    continue;
                }
                switch (r2["Content"].ToString())
                {
                    case "文件":
                        path = FileHelper.GetExistsPath(path.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                        if (path.Length == 0)
                        {
                            lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = "warning", Tag = r2["Content"] });
                            continue;
                        }
                        if (string.IsNullOrEmpty(r2["IconPath"].ToString()) || !File.Exists(r2["IconPath"].ToString()))
                        {
                            icon = null;
                        }
                        else
                        {
                            icon = Bitmap.FromFile(r2["IconPath"].ToString());
                        }
                        if (icon == null)
                        {
                            lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = "file", Tag = r2["Content"] });
                        }
                        else
                        {
                            imgs.Images.Add(title, icon);
                            lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = title, Tag = r2["Content"] });
                        }
                        break;
                    case "网址":
                        lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = "link", Tag = r2["Content"] });
                        lv.Items.Add(r2["ID"].ToString(), title, "link");
                        break;
                    case "目录":
                        lv.Items.Add(new ListViewItem() { Name = r2["ID"].ToString(), Text = title, ToolTipText = r2["Name"].ToString(), ImageKey = "folder", Tag = r2["Content"] });
                        break;
                }
            }
            lv.ResumeLayout();
        }
        private void cmiClickConfig()
        {
            #region cmsIcon
            cmiico新增ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico编辑ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico打开目录ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico排序后移ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico排序前移ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico删除ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico刷新ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            cmiico运行ToolStripMenuItem.Click += new EventHandler(cmsIcon_Click);
            #endregion
        }

        // 右键菜单打开时判断子菜单的显示
        private void cmsIcon_Opening(object sender, EventArgs e)
        {
            ListView lv = (ListView)(((ContextMenuStrip)sender).SourceControl);
            bool ischecked = lv.SelectedItems.Count > 0;
            cmiico新增ToolStripMenuItem.Visible = !ischecked;
            cmiico打开目录ToolStripMenuItem.Visible = ischecked;
            cmiico编辑ToolStripMenuItem.Visible = ischecked;
            cmiico排序后移ToolStripMenuItem.Visible = ischecked;
            cmiico排序前移ToolStripMenuItem.Visible = ischecked;
            cmiico删除ToolStripMenuItem.Visible = ischecked;
            cmiico运行ToolStripMenuItem.Visible = ischecked;
        }

        private void btn_Click(object sender, EventArgs e)
        {
            if (((Button)sender).Name == "btnNext")
            {
                tabctrlMain.SelectNextTab();
            }
            else
            {
                tabctrlMain.SelectPrevTab();
            }
        }

        // 获取当前选中的图标
        private ListViewItem GetCurrentIconByContextMenu(ToolStripMenuItem mi)
        {
            ListView lv = mi.GetSourceControl<ListView>();
            return lv == null || lv.SelectedItems.Count == 0 ? null : lv.SelectedItems[0];
        }

        // 图标右键点击事件
        private void cmsIcon_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            ListViewItem li = GetCurrentIconByContextMenu(mi);
            switch (mi.Name)
            {
                case "cmiico新增ToolStripMenuItem":
                    this.EditItem();
                    break;
                case "cmiico编辑ToolStripMenuItem":
                    if (li != null) EditItem(li.Name.ToInt());
                    break;
                case "cmiico打开目录ToolStripMenuItem":
                    if (li != null) OpenFolder(li.Name.ToInt());
                    break;
                case "cmiico排序后移ToolStripMenuItem":
                    if (li != null) MoveNext(li);
                    break;
                case "cmiico排序前移ToolStripMenuItem":
                    if (li != null) MovePrev(li);
                    break;
                case "cmiico删除ToolStripMenuItem":
                    if (li != null)
                    {
                        adh.ExecuteNonQuery("delete from tquickdial where ID=" + li.Name);
                        FormLoad();
                    }
                    break;
                case "cmiico刷新ToolStripMenuItem":
                    FormLoad();
                    break;
                case "cmiico运行ToolStripMenuItem":
                    StartApp();
                    break;
            }
        }

        // 选项卡切换事件
        private void tabctrlMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabctrlMain.SelectedIndex < 1) return;
            currentTabIndex = tabctrlMain.SelectedIndex;
            FormLoad_Icons();
        }

        // 图标容器鼠标点击事件
        private void lv_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) return;
            ceh.CheckClick();
        }

        // 图标双击-打开程序所在目录
        private void lvDoubleClick()
        {
            StartApp();
        }
        #region 方法

        // 获取当前选项卡中的图标容器
        private ListView GetListView()
        {
            if (tabctrlMain.SelectedTab == null) return null;
            if (tabctrlMain.SelectedTab.Tag == null)
            {
                MessageBox.Show("标签类型未设置");
                return null;
            }
            ListView lv = (ListView)tabctrlMain.SelectedTab.Controls[0];
            if (lv.SelectedItems.Count == 0) return null;
            return lv;
        }

        // 打开图标所在目录
        private void OpenIconFolder()
        {
            ListView lv = GetListView();
            if (lv == null) return;
            OpenFolder(lv.SelectedItems[0].Name.ToInt());
        }

        // 添加子项目
        private void EditItem(int id = 0)
        {
            switch (tabctrlMain.SelectedTab.Tag.ToString())
            {
                case "文件":
                    this.OpenDialog<frmAppEdit>(() => new frmAppEdit() { RecordTags = tabctrlMain.SelectedTab.Text, RecordID = id });
                    break;
                case "网址":
                    this.OpenDialog<frmUrlEdit>(() => new frmUrlEdit() { RecordTags = tabctrlMain.SelectedTab.Text, RecordID = id });
                    break;
                case "目录":
                    this.OpenDialog<frmFolderEdit>(() => new frmFolderEdit() { RecordTags = tabctrlMain.SelectedTab.Text, RecordID = id });
                    break;
            }
        }

        // 运行程序
        private void StartApp()
        {
            ListView lv = (ListView)tabctrlMain.SelectedTab.Controls[0];
            if (lv == null) return;
            ListViewItem li = lv.SelectedItems[0];
            if (li.Tag == null)
            {
                MessageBox.Show("标签类型未设置");
                return;
            }
            string iconType = li.Tag.ToString();
            DataTable dt = adh.ExecuteDataTable("select a.Paths,a.IconPath,b.Content from tquickdial a left join tgeneralcatalog b on a.Tags=b.Name where a.ID=" + li.Name);
            string paths = dt.Rows[0][0].ToString();
            if (paths.Length == 0) return;
            string path;
            string msg = StartApp(paths, iconType,out path);
            if (msg == "SUCCESS")
            {
                // 添加到收藏夹
                string fn = Path.GetFileNameWithoutExtension(path);
                if (adh.SelectDataTable("tAppFavorite", string.Format("Name='{0}'", fn), "_id").Rows.Count == 0)
                {
                    adh.Insert("tAppFavorite", "Name, Path, IconPath, Tags", string.Format("'{0}','{1}','{2}','{3}'", fn, paths, dt.GetValue<string>("IconPath"), iconType));
                    if (adh.MessageSet.Count > 0) MessageBox.Show(adh.MessageSet.ToString(","));
                }
                if (StartIconHandler != null) StartIconHandler(li.Text, paths, iconType, imgs.Images[li.Text]);
            }
            else
            {
                MessageBox.Show(msg);
            }
        }

        /// <summary>
        /// 运行程序,成功则返回SUCCESS,否则返回错误信息.
        /// <para>tag:文件|网址|目录</para>
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="tag"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public string StartApp(string paths, string tag,out string path)
        {
            path = string.Empty;
            if (string.IsNullOrEmpty(paths) || string.IsNullOrEmpty(tag)) return "参数无效!";
            switch (tag)
            {
                case "文件":
                    path = FileHelper.GetExistsPath(paths.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                    if (path.Length == 0) return "路径不存在!";
                    System.Diagnostics.Process.Start(path);
                    break;
                case "网址":
                    path = paths;
                    System.Diagnostics.Process.Start(paths);
                    break;
                case "目录":
                    path = FileHelper.GetExistsPath(paths.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries), "folder");
                    if (path.Length == 0) return "目录不存在";
                    System.Diagnostics.Process.Start(path);
                    break;
            }
            return "SUCCESS";
        }

        /// <summary>
        /// 运行程序,成功则返回SUCCESS,否则返回错误信息.
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public string StartApp(string paths, string tag)
        {
            string path;
            return StartApp(paths, tag, out path);
        }

        // 打开文件所在的目录
        private void OpenFolder(int id)
        {
            DataTable dt = adh.ExecuteDataTable("select Paths from tquickdial where ID=" + id);
            string paths = dt.Rows[0][0].ToString();
            if (paths.Length == 0) return;
            paths = System.IO.Path.GetDirectoryName(paths);
            if (paths.Length > 0) System.Diagnostics.Process.Start(paths);
        }

        // 图标前移
        private void MovePrev(ListViewItem li)
        {
            int i = li.Index;
            if (i == 1) return;
            ListViewItem btnPrev = (ListViewItem)li.ListView.Items[i - 1];
            int ordinal = adh.ExecuteDataTable("select Ordinal from tquickdial where ID=" + btnPrev.Tag).Rows[0][0].ToString().ToInt();

            adh.Update("tquickdial", "Ordinal=" + (ordinal + 1), "ID=" + btnPrev.Name);
            adh.Update("tquickdial", "Ordinal=" + ordinal, "ID=" + li.Name);
            FormLoad_Icons();
        }

        // 图标后移
        private void MoveNext(ListViewItem li)
        {
            int i = li.Index;
            if (i == li.ListView.Items.Count) return;
            ListViewItem btnNext = (ListViewItem)li.ListView.Items[i + 1];
            int ordinal = adh.ExecuteDataTable("select Ordinal from tquickdial where ID=" + btnNext.Tag).Rows[0][0].ToString().ToInt();

            adh.Update("tquickdial", "Ordinal=" + (ordinal - 1), "ID=" + btnNext.Name);
            adh.Update("tquickdial", "Ordinal=" + ordinal, "ID=" + li.Name);
            FormLoad_Icons();
        }
        #endregion

    }
}
